<?php


namespace App\Service;

use App\Utils\CustomUtils;
use Hyperf\Utils\Context;
use Psr\Http\Message\ServerRequestInterface;
use Swlib\SaberGM;

/**
 * Class CommonRiskService
 * 风控相关
 *
 * @package App\Service
 */
class CommonRiskService {

    protected const TIME_OUT = 20;

    const URI_RISK_AND_DISPATCH     = "/api/check/riskAndDispatch";
    const URI_RECOVER_CHANNEL_LIMIT = "/api/sync/recoverChannelLimit";
    const URI_RISK_RULE_MCH_REF_SET_BIND = "/admin/api/riskRuleMchRef/setBind";

    public function riskAndDispatch ($params) {

        $result = null;

        try {

            $api = env('RISK_CONTROL_URL').self::URI_RISK_AND_DISPATCH;

            $result = SaberGM::post($api, $params, ['timeout' => self::TIME_OUT])->getBody()->getContents();

        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
        }

        if (!$result) {
            throw new \Exception(trans('pay.risk.no_response'));
        }

        $result = json_decode($result, true);

        return $result;
    }

    public function recoverChannelLimit ($params) {
        $result = null;

        try {

            $api = env('RISK_CONTROL_URL').self::URI_RECOVER_CHANNEL_LIMIT;

            $result = SaberGM::post($api, $params, ['timeout' => self::TIME_OUT])->getBody()->getContents();

        } catch (\Throwable $e) {
        }

        if (!$result) {
            throw new \Exception(trans('pay.risk.cost.restore_fail'));
        }

        $result = json_decode($result, true);

        return $result;
    }

    public function riskRuleMchRefSetBind ($params) {

        $result = null;
        try {

            $api = env('RISK_CONTROL_URL').self::URI_RISK_RULE_MCH_REF_SET_BIND;
            $request = Context::get(ServerRequestInterface::class);
            $Authorization = $request->getHeader("Authorization")[0];
            $result = SaberGM::post($api, $params, ['timeout' => self::TIME_OUT, 'header' =>['Authorization' => $Authorization]])->getBody()->getContents();

        } catch (\Throwable $e) {
        }

        if (!$result) {
            throw new \Exception('请求调用风控模块失败');
        }

        $result = json_decode($result, true);

        return $result;
    }
}
